/**
 * 创建邮件配置页面
 */
import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Alert,
  Divider,
} from 'antd';
import { ArrowLeftOutlined, ApiOutlined, MailOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import {
  createEmailConfig,
  testEmailConfig,
  type EmailConfigCreate,
  type EmailConfigTest,
  EncryptionType,
} from '@/services/emailConfig';

const { Option } = Select;
const { TextArea } = Input;

const CreateEmailConfig: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [testLoading, setTestLoading] = useState(false);
  const [testResult, setTestResult] = useState<any>(null);

  // 处理表单提交
  const handleSubmit = async (values: EmailConfigCreate) => {
    setLoading(true);
    try {
      await createEmailConfig(values);
      message.success('邮件配置创建成功');
      history.push('/email-configs');
    } catch (error: any) {
      message.error(error.message || '创建失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理连接测试
  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields([
        'smtp_host',
        'smtp_port',
        'username',
        'password',
        'from_email',
        'encryption',
        'timeout',
      ]);

      setTestLoading(true);
      setTestResult(null);

      const testData: EmailConfigTest = {
        smtp_host: values.smtp_host,
        smtp_port: values.smtp_port,
        username: values.username,
        password: values.password,
        from_email: values.from_email,
        encryption: values.encryption,
        timeout: values.timeout,
      };

      const result = await testEmailConfig(testData);
      setTestResult(result);

      if (result.success) {
        message.success(result.message);
      } else {
        message.error(result.message);
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写完整的SMTP配置信息');
      } else {
        message.error(error.message || '连接测试失败');
      }
    } finally {
      setTestLoading(false);
    }
  };

  // 预设配置
  const presetConfigs = [
    {
      name: 'QQ邮箱 (SSL)',
      smtp_host: 'smtp.qq.com',
      smtp_port: 465,
      encryption: EncryptionType.SSL,
    },
    {
      name: 'QQ邮箱 (STARTTLS)',
      smtp_host: 'smtp.qq.com',
      smtp_port: 587,
      encryption: EncryptionType.STARTTLS,
    },
    {
      name: '163邮箱',
      smtp_host: 'smtp.163.com',
      smtp_port: 465,
      encryption: EncryptionType.SSL,
    },
    {
      name: 'Gmail',
      smtp_host: 'smtp.gmail.com',
      smtp_port: 587,
      encryption: EncryptionType.STARTTLS,
    },
  ];

  // 应用预设配置
  const applyPresetConfig = (preset: any) => {
    form.setFieldsValue({
      smtp_host: preset.smtp_host,
      smtp_port: preset.smtp_port,
      encryption: preset.encryption,
    });
    setTestResult(null);
  };

  return (
    <PageContainer
      header={{
        title: '创建邮件配置',
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/email-configs')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            smtp_port: 587,
            encryption: EncryptionType.STARTTLS,
            timeout: 30,
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="配置名称"
                rules={[
                  { required: true, message: '请输入配置名称' },
                  { min: 2, message: '配置名称至少需要2个字符' },
                ]}
              >
                <Input placeholder="请输入配置名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="description" label="配置描述">
                <Input placeholder="请输入配置描述（可选）" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">SMTP服务器配置</Divider>

          {/* 预设配置快速选择 */}
          <Alert
            message="快速配置"
            description={
              <Space wrap>
                {presetConfigs.map((preset, index) => (
                  <Button
                    key={index}
                    size="small"
                    onClick={() => applyPresetConfig(preset)}
                  >
                    {preset.name}
                  </Button>
                ))}
              </Space>
            }
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Row gutter={24}>
            <Col span={16}>
              <Form.Item
                name="smtp_host"
                label="SMTP服务器地址"
                rules={[{ required: true, message: '请输入SMTP服务器地址' }]}
              >
                <Input placeholder="例如：smtp.qq.com" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="smtp_port"
                label="端口"
                rules={[
                  { required: true, message: '请输入端口号' },
                  { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="587"
                  min={1}
                  max={65535}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入SMTP用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password placeholder="请输入SMTP密码或授权码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="encryption"
                label="加密方式"
                rules={[{ required: true, message: '请选择加密方式' }]}
              >
                <Select placeholder="请选择加密方式">
                  <Option value={EncryptionType.NONE}>无加密</Option>
                  <Option value={EncryptionType.SSL}>SSL</Option>
                  <Option value={EncryptionType.STARTTLS}>STARTTLS</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="timeout"
                label="连接超时时间（秒）"
                rules={[
                  { required: true, message: '请输入超时时间' },
                  { type: 'number', min: 5, max: 300, message: '超时时间必须在5-300秒之间' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="30"
                  min={5}
                  max={300}
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">发件人信息</Divider>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="from_email"
                label="发件人邮箱"
                rules={[
                  { required: true, message: '请输入发件人邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input placeholder="请输入发件人邮箱地址" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="from_name" label="发件人姓名">
                <Input placeholder="请输入发件人姓名（可选）" />
              </Form.Item>
            </Col>
          </Row>

          {/* 连接测试结果 */}
          {testResult && (
            <Alert
              message={testResult.success ? '连接测试成功' : '连接测试失败'}
              description={testResult.message}
              type={testResult.success ? 'success' : 'error'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Form.Item>
            <Space>
              <Button
                type="default"
                icon={<ApiOutlined />}
                onClick={handleTestConnection}
                loading={testLoading}
              >
                测试连接
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                创建配置
              </Button>
              <Button onClick={() => history.push('/email-configs')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default CreateEmailConfig;
